package com.qcq.wecheck.controller;


import com.qcq.wecheck.entity.User;
import com.qcq.wecheck.result.CommonResult;
import com.qcq.wecheck.service.UserService;
import com.qcq.wecheck.service.WebService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author O
 * @since 2018-09-19
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	@Resource
	private WebService webService;

	/**
	 * 根据openId注册用户基本信息
	 *
	 * @param user user
	 * @return json
	 */
	@PostMapping
	public CommonResult register(@Validated User user, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return CommonResult.failure(bindingResult.getFieldError().getDefaultMessage());
		}
		user.setCreateTime(LocalDateTime.now())
				.setLastLoginTime(LocalDateTime.now());
		if (user.getTel() == null) {
			user.setTel("未填写");
		}
		if (userService.selectById(user.getOpenId()) != null) {
			return CommonResult.failure("openId已经存在,不可再次注册");
		}
		if (userService.insert(user)) {
			return CommonResult.success();
		}
		return CommonResult.failure();
	}

	/**
	 * 条件更新
	 *
	 * @param user user
	 * @return json
	 */
	@PutMapping
	public CommonResult update(User user) {
		if (user.getOpenId() == null) {
			return CommonResult.failure("openId不能为空");
		}
		if (userService.updateById(user)) {
			return CommonResult.success();
		}
		return CommonResult.failure();
	}

	/**
	 * 获取单个user
	 *
	 * @param openId openId
	 * @return json
	 */
	@GetMapping
	public CommonResult getUser(@RequestParam("openId") String openId) {
		User user = userService.selectById(openId);
		return user == null ? CommonResult.failure("用户不存在") : CommonResult.success(user);
	}

	/**
	 * 获取腾讯平台的openId
	 */
	@GetMapping("openId")
	public CommonResult getOpenId(@RequestParam("jsCode") String jsCode) {
		String openId = webService.getOpenId(jsCode);
		return openId != null ? CommonResult.success(openId) : CommonResult.failure("获取失败");
	}
}
